package com.zyzg.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    /**
     * 生成 AES 密钥
     * @return 生成的密钥的 Base64 编码字符串
     * @throws Exception 异常
     */
    public static String generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * 使用 AES 加密字符串
     * @param plainText 明文
     * @param key 密钥的 Base64 编码字符串
     * @return 加密后的 Base64 编码字符串
     * @throws Exception 异常
     */
    public static String encrypt(String plainText, String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 使用 AES 解密字符串
     * @param encryptedText 加密后的 Base64 编码字符串
     * @param key 密钥的 Base64 编码字符串
     * @return 解密后的明文
     * @throws Exception 异常
     */
    public static String decrypt(String encryptedText, String key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(key);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
//            System.out.println("AES-key:"+generateKey());
//            System.out.println("加密："+encrypt("kpbTVuxWaHz2MEilFmqjJGQtgTYtE78i0G57UyVP2Q","uKvJjo+ADHcoFlDHTwzb7Q=="));
//            System.out.println("解密："+decrypt("j5G0f2J2NQ7uUs04UCiXDA==","3lyv0XQ6El68oQmOchzgUQ=="));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}